package com.example.wacoffee_user.controller;

import cn.hutool.core.util.RandomUtil;
import com.example.wacoffee_user.pojo.vo.registerVo;
import com.example.wacoffee_user.utils.CurrentHoler;
import com.example.wacoffee_user.utils.MailUtil;
import com.example.wacoffee_user.utils.Result;
import io.netty.util.Timeout;
import jakarta.annotation.Resource;
import org.apache.commons.mail.Email;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Random;

@RestController
public class mailController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @PostMapping("/getCode")
    public Result mail(@RequestBody registerVo registerVo){
        System.out.println(registerVo);
        String targetEmail=registerVo.getEmail();
        // 校验邮箱格式
        if (targetEmail == null || !targetEmail.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")) {
            return Result.error("邮箱格式不正确");
        }
        // 校验是否是 QQ 邮箱
        if (!targetEmail.endsWith("@qq.com")) {
            return Result.error("仅支持 QQ 邮箱");
        }
        String authCode= RandomUtil.randomNumbers(6);

        if(stringRedisTemplate.opsForValue().get("authCode:"+targetEmail)!=null)return Result.error("请勿重复获取验证码");
        else stringRedisTemplate.opsForValue().set("authCode:"+targetEmail,authCode, Duration.of(3, ChronoUnit.MINUTES));
        MailUtil.sendEmailCode(targetEmail,authCode);
        return Result.success();
    }
}
